<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" @click="log = true">查看日志</el-button>
    </div>
    <panel-group :value="devices" @handleSetLineChartData="handleSetLineChartData" />

    <div>
      <el-row :gutter="32">
        <div v-for="(item, index) in devices" :key="index">
          <!-- 红外 -->
          <el-col v-if="item.model==='rg601'" :span="6" style="margin-bottom:30px;">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span class="card-header">{{ item.name }}({{ item.position }})</span>
                <el-tag v-if="item.online === 1" type="success" style="float: right; "> 在线 </el-tag>
                <el-tag v-else type="danger" style="float: right; "> 离线 </el-tag>
              </div>
              <infrared :data="item" :sub="item.sub" />
            </el-card>
          </el-col>
          <!-- 门禁 -->
          <el-col v-if="item.model==='rg602'" :span="6" style="margin-bottom:30px;">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span class="card-header">{{ item.name }}({{ item.position }})</span>
                <el-tag v-if="item.online === 1" type="success" style="float: right; "> 在线 </el-tag>
                <el-tag v-else type="danger" style="float: right; "> 离线 </el-tag>
              </div>
            </el-card>
          </el-col>
          <!-- 移动轴 -->
          <el-col v-if="item.model==='rg603' || item.model==='rg604'" :span="6" style="margin-bottom:30px;">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span class="card-header">{{ item.name }}</span>
                <el-tag v-if="item.online === 1" type="success" style="float: right; "> 在线 </el-tag>
                <el-tag v-else type="danger" style="float: right; "> 离线 </el-tag>
              </div>
              <el-button class="filter-item" type="primary" size="mini" style="float:right;" @click="item.drawer = true">操作</el-button>
              <el-table
                :data="item.value.axis"
                :show-header="false"
                style="width: 100%"
              >
                <el-table-column prop="name" label="轴名称" align="center" />
                <el-table-column prop="start" label="当前位置" align="center" />
              </el-table>
              <el-drawer
                :visible.sync="item.drawer"
                :with-header="false"
                direction="btt"
                :append-to-body="true"
                size="60%"
              >
                <track-axis :value="item.value" :sub="item.sub" />
              </el-drawer>
            </el-card>
          </el-col>

        </div>
      </el-row>
    </div>

    <el-drawer
      title="运行日志"
      :visible.sync="log"
      :with-header="false"
      direction="rtl"
      :append-to-body="true"
      size="60%"
    >
      <emqx-log />
    </el-drawer>

  </div>
</template>

<script>
import { getDevices } from '@/api/device'
import { emqxCheckOnline } from '@/api/emqx'
import waves from '@/directive/waves' // waves directive

import TrackAxis from './components/TrackAxis'
// import CircleAxis from './components/CircleAxis'
import EmqxLog from './components/EmqxLog'
import Infrared from './components/Infrared'
import PanelGroup from './components/PanelGroup'

export default {
  name: 'XRay',
  components: {
    Infrared,
    TrackAxis,
    EmqxLog,
    PanelGroup
  },
  directives: { waves },
  filters: {
    typeFilter(status) {
      if (status === 1) {
        return 'success'
      } else {
        return 'danger'
      }
    },
    statusFilter(status) {
      if (status === 1) {
        return '正常'
      } else {
        return '异常'
      }
    },
    onlineTypeFilter(status) {
      if (status === 1) {
        return 'success'
      } else {
        return 'danger'
      }
    },
    onlineFilter(status) {
      if (status === 1) {
        return '在线'
      } else {
        return '离线'
      }
    }
  },
  data() {
    return {
      value: true,
      log: false,
      tableKey: 0,
      devicesLoading: false,
      devices: [],
      status: {
        temperature: 23.5,
        dampness: 23.5,
        pressure: 100
      },
      sourceTimerChecked: false,
      sourceTimerInterval: 0,
      // 轨道
      dialogTrackVisible: false,
      track: {},
      // 圆盘
      dialogCircleVisible: false,
      circle: { axis: [{ start: 10, split_number: 10 }] }
    }
  },
  created() {
    this.fetchData()
    // this.handleFilter()
  },
  methods: {
    fetchData() {
      this.devicesLoading = true
      getDevices().then(response => {
        this.devicesLoading = false
        var data = response.data
        for (var i = 0; i < data.length; i++) {
          data[i].value = JSON.parse(data[i].value)
          data[i].drawer = false
        }
        data.sort(function(a, b) {
          return a.model - b.model
        })
        this.devices = data
        console.log(this.devices)

        this.doSubscribe()
        this.checkOnline()
      })
    },
    // 检查设备是否在线
    checkOnline() {
      emqxCheckOnline().then(response => {
        console.log('查询在线结果')
        console.log(response)
        if (response.code === 20000) {
          var data = JSON.parse(response.data).data
          for (var i = 0; i < this.devices.length; i++) {
            var online = 0
            var device = this.devices[i]
            for (var j = 0; j < data.length; j++) {
              var item = data[j]
              if (item.connected) {
                if (item.clientid === device.sn) {
                  online = 1
                }
              }
            }
            this.devices[i].online = online
          }
        }
      })
    },

    // 红外获取是否有人
    InfraredGetPeople(item) {
      item.value.people = 0
      var message = {
        code: item.value.code_get_people.toString(),
        msg: '0'
      }
      this.publish(item.sub, JSON.stringify(message))
    },

    // mqtt相关操作
    doSubscribe() {
      console.log('订阅主题')
      var data = this.devices
      for (var i = 0; i < data.length; i++) {
        var topic = data[i].pub
        console.log(topic)
        this.$mqtt.subscribe(topic)
      }
    },

    subscribe(val) {
      this.$mqtt.subscribe(val)
    },
    publish(topic, message) {
      console.log('推送消息')
      console.log('topic:' + topic)
      console.log('message:' + message)
      this.$mqtt.publish(topic, message)
    }
  },
  mqtt: {
    '#'(data, topic) {
      // this.mqttLogs.push({
      //   topic: topic,
      //   msg: String.fromCharCode.apply(null, data),
      //   time: ''
      // })
      console.log('收到消息')
      console.log('topic:' + topic)
      console.log('payload: ' + String.fromCharCode.apply(null, data))
      var patt = /^fsc\/(rg[0-9]{0,10})\/([0-9a-zA-Z]{0,32})\/tx$/
      var res = patt.exec(topic)
      if (res) {
        try {
          var model = res[1]
          var sn = res[2]
          console.log('型号:' + model)
          console.log('SN:' + sn)
          var info = JSON.parse(data)
          var aswcode = parseInt(info.aswcode)
          var aswmsg = info.aswmsg
          var i = 0
          for (i = 0; i < this.devices.length; i++) {
            var device = this.devices[i]
            if (device.sn === sn) {
              // 红外
              if (device.model === 'rg601') {
                console.log('红外设备信息处理')
                if (aswcode === parseInt(device.value.code_get_people)) {
                  console.log(aswmsg)
                  this.devices[i].value.people = parseInt(aswmsg)
                }
              }

              var j = 0
              // 轨道数据处理
              if (device.model === 'rg603') {
                console.log('轨道数据处理')
                for (j = 0; j < device.value.axis.length; j++) {
                  // console.log(device.value.axis[j])
                  if (device.value.axis[j].get_position_code === aswcode) {
                    this.$message({ message: '正在移动中', type: 'success' })
                    device.value.axis[j].start = aswmsg
                  }
                  if (device.value.axis[j].move_code === aswcode) {
                    if (aswmsg === 0) {
                      this.$message({ message: '警告，当前轴电机处于运行状态', type: 'warning' })
                    }
                    if (aswmsg === 1) {
                      this.$message({ message: '成功，当前轴电机开始运行', type: 'success' })
                    }
                  }
                }
              }
              // 圆盘数据处理
              if (device.model === 'rg604') {
                console.log('接收数据【rg604】')
                for (j = 0; j < device.value.axis.length; j++) {
                  if (device.value.axis[j].get_position_code === aswcode) {
                    this.$message({ message: '正在移动中', type: 'success' })
                    console.log(aswmsg)
                    device.value.axis[j].start = parseInt(aswmsg)
                  }
                  if (device.value.axis[j].move_code === aswcode) {
                    if (aswmsg === 0) {
                      this.$message({ message: '警告，当前轴电机处于运行状态', type: 'warning' })
                    }
                    if (aswmsg === 1) {
                      this.$message({ message: '成功，当前轴电机开始运行', type: 'success' })
                    }
                  }
                }
              }
              // 圆盘数据处理
              break
            }
          }
        } catch (e) {
          console.log(e)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.panel-group {
  margin-top: 18px;

  .card-panel-col {
    margin-bottom: 32px;
  }
  .card-axis {
    height: 100%;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
    border-color: rgba(0, 0, 0, .05);
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
    border-color: rgba(0, 0, 0, .05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }

      .icon-people {
        background: #40c9c6;
      }

      .icon-message {
        background: #36a3f7;
      }

      .icon-money {
        background: #f4516c;
      }

      .icon-shopping {
        background: #34bfa3
      }
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-money {
      color: #f4516c;
    }

    .icon-shopping {
      color: #34bfa3
    }

    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-icon {
      float: left;
      font-size: 48px;
    }

    .card-panel-description {
      float: right;
      font-weight: bold;
      margin: 26px;
      margin-left: 0px;

      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-online {
        line-height: 18px;
        color: rgba(0, 255, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-offline {
        line-height: 18px;
        color: rgba(255, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}

@media (max-width:550px) {
  .card-panel-description {
    display: none;
  }

  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>
